﻿package  {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	import flash.ui.Mouse;
	
	
	public class Main extends MovieClip {
		
		
		public function Main() {
			trace("So it begins!");
			
			init();
		}
		
		public var ball:MovieClip;
		public var board:MovieClip;
		private var speedX:Number = 15;
		private var speedY:Number = 15;
		/**
		 * 砖块数组 
		 */		
		private var brickArr:Array = [];
		/**
		 * 初始化
		 * 
		 */		
		private function init():void
		{
			//初始化小球
			ball.x = stage.stageWidth / 2;
			ball.y = stage.stageHeight / 2;
			//初始化砖块
			for(var j:int=0; j<5; j++)
			{
				for(var i:int=0; i<8; i++)
				{
					var brick:MovieClip = new Brick();
					addChild( brick );
					brick.x = 10 + 70 * i;
					brick.y = 10 + 35 * j;
					
					brickArr.push( brick );
					
					var color:ColorTransform = new ColorTransform( Math.random(),
						Math.random(), Math.random() );
					brick.transform.colorTransform = color;
				}
			}
			
			//初始化挡板 
			board.x = stage.stageWidth / 2;
			board.y = 380;
			// 隐藏鼠标
			//Mouse.hide();
			
			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		protected function update(event:Event):void
		{
			// 挡板运动
			board.x = mouseX;
			
			if( board.x < board.width / 2 )
			{
				board.x = board.width / 2;
			}else if( board.x > stage.stageWidth -  board.width / 2 )
			{
				board.x = stage.stageWidth - board.width / 2
			}
			// 小球运动
			ball.x += speedX;
			ball.y += speedY;
			
			if( ball.x < ball.width / 2 )
			{
				ball.x = ball.width / 2;
				speedX *= -1;
			}else if( ball.x > stage.stageWidth -  ball.width / 2 )
			{
				ball.x = stage.stageWidth -  ball.width / 2;
				speedX *= -1;
			}
			
			if( ball.y < ball.width / 2 )
			{
				ball.y = ball.width / 2;
				speedY *= -1;
			}else if( ball.y > stage.stageHeight -  ball.width / 2 )
			{
				ball.y = stage.stageHeight -  ball.width / 2;
				speedY *= -1;
			}
			// 小球和挡板碰撞检测（小球速度变化（反向））
			if( ball.hitTestObject( board ) )
			{
				speedY *= -1;
				speedX = ( ball.x - board.x ) * 0.2;
			}
			// 小球和砖块碰撞检测
			for(var i:int= brickArr.length - 1; i>=0; i--)
			{
				var brick:MovieClip = brickArr[i];
				if( ball.hitTestObject( brick ) )
				{
					//小球速度变化（反向）
					speedY *= -1;
					//方块消失
					removeChild( brick );
					// 
					brickArr.splice( i, 1 );
					//掉道具（*）
				}
			}
			
		}
	}
	
}
